﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Web.Utils;
using Legazpi.Payroll.DataAccess.DataObjects;
using System.Linq;
using Newtonsoft.Json;

namespace Legazpi.Payroll.Web.Admin
{
    public partial class EmployeeEntry : System.Web.UI.Page
    {
        [Inject]
        public IEmployeeService _employeeService { get; set; }

        [Inject]
        public ISectorService _sectorService { get; set; }

        [Inject]
        public IDetachmentService _detachmentService { get; set; }

        public bool IsSuccess { get; set; }
        public string NotifyText { get; set; }

        private int _currentEmployeeId;
        public int CurrentEmployeeId
        {
            get
            {
                int id;
                return int.TryParse(EmployeeIdHidden.Value, out id) ? id : 0;
            }
            set
            {
                _currentEmployeeId = value;
                EmployeeIdHidden.Value = _currentEmployeeId.ToString();
            }
        }

        #region Implementations
        void BindDropdowns()
        {
            DropDownHelper.ConstructDateDropdowns(MonthDroplist, DayDroplist, YearDroplist, null);  
            //Positions                                              
            PositionDropList.ToPositionSelectList(0);
            //Clients/Deployed At            
            DeployedDropList.ToSectorSelectList(0);
            ////Supervisors
            //SupervisorDropdown.ToSuperVisorSelectList(Model.SupervisorId.GetValueOrDefault(0));
            ////Employee Status
            EmployedStatusDropDown.ToEmployeeStatusSelectList(0);            
        }
        void Edit(int id)
        {
            var employee = _employeeService.GetById(id);
            if (employee == null)
                return;

            PositionDropList.ClearSelection();
            DeployedDropList.ClearSelection();
            EmployedStatusDropDown.ClearSelection();

            ObjectToData(employee);

            CurrentEmployeeId = id;
            SubmitBtn.Text = "Update & ClearForm";
            SubmitBtn2.Text = "Update";
        }

        void Update(int id)
        {
            var employee = _employeeService.GetById(id);
            if (employee == null)
            {
                Add();
                return;
            }
            DataToObject(ref employee);

            _employeeService.Update(employee);
            IsSuccess = _employeeService.Save();
            NotifyText = "Successfully Updated Record.";
        }
        void Add()
        {
            var employee = new Employee();

            DataToObject(ref employee);

            _employeeService.Add(employee);
            IsSuccess = _employeeService.Save();

            CurrentEmployeeId = employee.Id;
            NotifyText = "Successfully Added New Record.";
            SubmitBtn.Text = "Update & ClearForm";
            SubmitBtn2.Text = "Update";

        }
        void ClearForm()
        {
            ClearControl(this.Page);
            CurrentEmployeeId = 0;
            SubmitBtn.Text = "Submit & ClearForm";
            SubmitBtn2.Text = "Submit";
        }
        void ClearControl(Control ctrl)
        {
            foreach (Control _ctrl in ctrl.Controls)
            {
                if (_ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)_ctrl).Text = string.Empty;
                }
                else if (_ctrl.GetType() == typeof(DropDownList))
                {
                    ((DropDownList)_ctrl).SelectedIndex = 0;
                }
                ClearControl(_ctrl);
            }
        }
        void Save()
        {
            if (CurrentEmployeeId == 0)
                Add();
            else
                Update(CurrentEmployeeId);
        }
        void DataToObject(ref Employee obj)
        {
            var dob = new DateTime(int.Parse(YearDroplist.SelectedValue),
                int.Parse(MonthDroplist.SelectedValue),
                int.Parse(DayDroplist.SelectedValue));

            obj.FirstName = FirstNameTxt.Text;
            obj.LastName = LastNameTxt.Text;
            obj.MiddleName = MidNameTxt.Text;
            obj.NickName = NickNameTxt.Text;

            obj.DateOfBirth = dob;
            obj.Gender = SexDropList.SelectedValue.ToString();
            obj.CivilStatus = CivilStatDropList.SelectedValue.ToString();
            obj.ContactNo = ContactTxt.Text;
            obj.Address = AddressTxt.Text;
            obj.Remarks = RemarksTxt.Text;
            obj.PlaceOfBirth = POBTxt.Text;
            obj.Religion = ReligionTxt.Text;

            //account
            obj.TinId = TaxIdTxt.Text;
            obj.SSSId = SSSIdNoTxt.Text;
            obj.PagIbigId = PagibigIdNoTxt.Text;
            obj.PhilHealthId = PhilHealthIdNoTxt.Text;

            //employment
            if (PositionDropList.SelectedIndex > 0)
                obj.PositionId = int.Parse(PositionDropList.SelectedValue);
            if (EmployedStatusDropDown.SelectedIndex > 0)
                obj.SetStatus(int.Parse(EmployedStatusDropDown.SelectedValue));
            if (DeployedDropList.SelectedIndex > 0 && obj.PositionId.HasValue)
            {
                var detachment = _detachmentService.GetByQuery(int.Parse(DeployedDropList.SelectedValue), obj.PositionId.Value);
                if (detachment != null)
                    obj.DetachmentId = detachment.Id;                
            }
            
        }

        void ObjectToData(Employee obj)
        {
            FirstNameTxt.Text = obj.FirstName;
            LastNameTxt.Text = obj.LastName;
            MidNameTxt.Text = obj.MiddleName;
            NickNameTxt.Text = obj.NickName;
            if (obj.DateOfBirth.HasValue)
            {
                YearDroplist.SelectedValue = obj.DateOfBirth.Value.Year.ToString();
                MonthDroplist.SelectedValue = obj.DateOfBirth.Value.Month.ToString("00");
                DayDroplist.SelectedValue = obj.DateOfBirth.Value.Day.ToString("00");
            }

            var gender = SexDropList.Items.FindByValue(obj.Gender);
            if (gender != null)
                gender.Selected = true;

            var civil = CivilStatDropList.Items.FindByValue(obj.CivilStatus);
            if (civil != null)
                civil.Selected = true;

            ContactTxt.Text = obj.ContactNo;
            AddressTxt.Text = obj.Address;
            RemarksTxt.Text = obj.Remarks;
            POBTxt.Text = obj.PlaceOfBirth;
            ReligionTxt.Text = obj.Religion;

            //account
            TaxIdTxt.Text = obj.TinId;
            SSSIdNoTxt.Text = obj.SSSId;            
            PagibigIdNoTxt.Text = obj.PagIbigId;
            PhilHealthIdNoTxt.Text = obj.PhilHealthId;

            //employment
            //position
            if (obj.PositionId.HasValue)
            {
                var posItem = PositionDropList.Items.FindByValue(obj.PositionId.Value.ToString());
                if (posItem != null)
                    posItem.Selected = true;
            }
            //employee status
            var statusItem = EmployedStatusDropDown.Items.FindByValue(obj.EmployedStatus.ToString());
            if (statusItem != null)
                statusItem.Selected = true;
            //deployed at
            if (obj.Detachment != null)
            {
                var detachItem = DeployedDropList.Items.FindByValue(obj.Detachment.SectorId.ToString());
                if (detachItem != null)
                    detachItem.Selected = true;            
            }
        }
        #endregion
        protected override void OnInit(EventArgs e)
        {
            int id = 0;
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                int.TryParse((string)Request.QueryString["id"], out id);

            CurrentEmployeeId = id;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {                
                BindDropdowns();
                if (CurrentEmployeeId > 0)
                    Edit(CurrentEmployeeId);
            }                
        }

        protected void SubmitBtn_Click(object sender, EventArgs e)
        {
            Save();
            Response.Redirect(Request.Path);
        }
        protected void SubmitBtn2_Click(object sender, EventArgs e)
        {
            Save();
        }
        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            ClearForm();
        }
        protected void SearchBtn_Click(object sender, EventArgs e)
        {
            if (CurrentEmployeeId > 0)
                Edit(CurrentEmployeeId);
        }
    }
}